
from pydantic import BaseModel
import random
from fastapi.responses import JSONResponse, FileResponse  # 导入FileResponse

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware  # 导入CORS中间件
from fastapi.responses import FileResponse  # 用于返回文件响应
import uvicorn

app = FastAPI()

# CORS中间件的设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法
    allow_headers=["*"],  # 允许所有头部
)

class Item(BaseModel):
    x: float
    y: float
    z: float

@app.get("/data")
async def get_data():
    return JSONResponse(content={"x": random.random(), "y": random.random(), "z": random.random()})

@app.get("/")
async def get_index():
    # 直接返回同目录下的index.html文件
    return FileResponse('index.html')

def main():
    # 使用uvicorn运行FastAPI应用，指定主机地址和端口
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")

if __name__ == "__main__":
    main()
